<template>
  <view class="content">
    <u-navbar is-back="true" title="经营一张图" :background="background"></u-navbar>
    <map
      id="map"
      show-location
      :latitude="latitude"
      :longitude="longitude"
      :polyline="polyline"
      :style="{ width: '100%', height: windowHeight + 'px' }"
      :scale="8"
      @markertap="markTap"
    ></map>
    <view class="searchBox rounded-8">
      <view class="d-flex a-center pt-3 ">
        <view style="z-index: 9;">
          <hpy-form-select
            :dataList="myPhaseList"
            text="label"
            name="value"
            v-model="tag"
            title="请选择项目阶段"
            hideBorder
            @change="changemyPhaseFn"
          />
        </view>
        <view class="u-m-l-10 flex-1" style="z-index: 9;">
          <u-search
            placeholder="搜索"
            placeholder-color="#86909c"
            bg-color="#f2f3f5"
            @search="searchKeyFn"
            v-model="projectName"
            :show-action="false"
          ></u-search>
        </view>
      </view>

      <view class="d-flex">
        <!-- <view
          class="date"
          style="line-height: 80rpx;"
          :style="{ color: color, fontWeight: fontWeight }"
          @click="acceptDatePickerFn"
        >
          <view class="pr d-flex ">
            反馈时间
            <view class="d-flex flex-column pl-1">
              <view
                class="iconfont icon-shangjiantou "
                :class="changeColor ? 'text-primary' : 'text-success'"
                style="height: 20rpx; font-size: 22rpx; margin-top: -6rpx;"
              ></view>
              <view
                class="iconfont icon-xiajiantou "
                :class="changeColor ? 'text-success' : 'text-primary'"
                style="height: 20rpx;font-size: 22rpx;margin-top: -6rpx;"
              ></view>
            </view>
          </view>
        </view> -->
        <view class="operateBox">
          <u-dropdown>
            <u-dropdown-item
              v-model="rootInformationEnum"
              :title="rootInformList[rootInformationEnum].label"
              :options="rootInformList"
              @change="changeRootInformationEnumFn"
            ></u-dropdown-item>
            <u-dropdown-item
              v-model="projectStage"
              :title="projectPhaseList[projectStage].label"
              :options="projectPhaseList"
              @change="changeProjectStageFn"
            ></u-dropdown-item>
          </u-dropdown>
        </view>
      </view>
    </view>
    
    <u-popup v-model="show" mode="bottom" width="85%" closeable border-radius="8">
      <view class="pt-6 pb-6 px-4 line-h-lg" @click="projectDetailsFn(selectedMarker)">
        <!-- <view class="font text-h">发布时间：{{ selectedMarker.createDateTime }}</view> -->
        <view class="d-flex j-sb a-center mt-2">
          <view class="font text-h">发布时间：{{ selectedMarker.createDateTime }}</view>
          <view class=" rounded  px-2 py-1 font" :class="[changeBg(selectedMarker)]">
            {{ selectedMarker.auditStatusName }}
          </view>
        </view>
        <view class="font-lg text-main font-weight">{{ selectedMarker.projectName }}</view>
        <view class="u-flex u-row-between">
          <view class="bg-grey  px-1 py text-primary font">{{ selectedMarker.rootInformationEnumName }}</view>
          <view class="text-primary font">
            <image
              class="imagesBox"
              mode="aspectFit"
              style="width: 46rpx ; height: 16rpx;"
              :src="getStaticFilePath('ico-jd.png')"
            ></image>
            {{ selectedMarker.projectStageName }}
          </view>
        </view>

        <view class="p-2 my-2 bg-grey rounded line-h-md">
          <view class="d-flex a-center">
            <view class="flex-1 ">
              <text class="text-tips font">信息类型：</text>
              <text class="text-main font ">{{ selectedMarker.infoTypeName }}</text>
            </view>
            <view class="flex-1">
              <text class="text-tips font">预计产值规模：</text>
              <text class="text-main font ">{{ selectedMarker.outputScale }}</text>
            </view>
          </view>
          <view class="d-flex a-center">
            <view class="flex-1">
              <text class="text-tips font">省份：</text>
              <text class="text-main font ">{{ selectedMarker.province }}</text>
            </view>
            <view class="flex-1">
              <text class="text-tips font">城市：</text>
              <text class="text-main font ">{{ selectedMarker.city }}</text>
            </view>
          </view>
          <view class="d-flex j-sb mt-2 a-center">
            <view class="d-flex a-center">
              <view class="iconfont icon-calendar-todo-fill text-primary"></view>
              <view class="text-main font ml-1">
                {{ selectedMarker.projectAddressName }}
              </view>
            </view>
          </view>
        </view>
        <view class="listBnt d-flex j-end a-center">
          <view class="d-flex a-center mr-1 font">
            <image :src="getStaticFilePath('go-address.png')" style="height: 32rpx; width: 32rpx; margin-right: 10rpx;"></image>
            距您{{ markerDistance >= 1000 ? `${(markerDistance / 1000).toFixed(1)}千米` : `${markerDistance}米` }}，驾车约{{ markerDuration }}
          </view>
          <button class="primaryMiniBnt btn-hollow mr-1" @click.stop="handleCallNavigator">
            导 航
          </button>
          <button class="primaryMiniBnt mr-1" style="width: auto;" @click.stop="projectDetailsFn(selectedMarker)">
            详 情
          </button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { convertMinutesToHours_minutes } from '@/utils/tool.js';
import { rootInformList, projectPhaseList } from '@/utils/data.js';
import { busiInfoMapGetByPage, busInfoTrackPageList } from '@/api/apis.js';

var QQMapWX = require('@/utils/qqmap-wx-jssdk.min.js');

class mapPlugin {
	/**
	 * 腾讯地图微信小程序API类
	 *
	 * @constructor
	 */
  constructor(param) {
    this.qqmapsdk = new QQMapWX({
      key: param.ak
    });
  }
  
  /**
   * @description 规划路线
   * @param {Object} param
   */
  execDirection(param) {
    var that = this;
    param = param || {};
    let params = {
      mode: 'driving',
      from: param.from,
      to: param.to,
    }
    let callbacks = {
      success: param['success'] || function() {},
      fail: param['fail'] || function(message) {
        console.log(message)
        uni.showToast({
          icon: 'none',
          title: message
        })
      }
    };
    that.qqmapsdk.direction({
      ...params,
      success: (data) => {
        if (data.status == 0) {
          callbacks.success(data);
        } else {
          callbacks.fail(data.message);
        }
      },
      fail: (err) => {
        callbacks.fail(JSON.stringify(err));
      }
    })
  }
}

export default {
	data() {
		return {
			background: {
				backgroundColor: '#fff'
			},
			_mapContext: null,
			windowHeight: 0,
			latitude: null,
			longitude: null,
			markers: [],
			selectedMarker: {},
			show: false,
			myPhaseList: [
				{
					label: '我发布的',
					value: 'iposted'
				},
				{
					label: '我跟踪的',
					value: 'ifollowed'
				}
			],
			rootInformList,
			projectPhaseList,
			color: 'rgb(96, 98, 102)',
			iconColor: '#c0c4cc',
			fontWeight: 'normal',
			changeColor: false,
			projectName: '',
			projectStage: 4, //项目阶段
			rootInformationEnum: 2, //信息源
			current: 1,
			tag: 'iposted',
      
      markerDuration: 0,
      markerDistance: 0,
      userLat: '',
      userLong: '',
      mapPlugin: null,
      polyline: [], //导航线
		};
	},
	onLoad() {},
	options: {
		styleIsolation: 'shared' // 解除样式隔离
	},
	onReady() {
		uni.getSystemInfo({
			success: res => {
				this.windowHeight = res.windowHeight;
			}
		});

		// 创建map对象
		this._mapContext = uni.createMapContext('map', this);
		this.cluster();
	},
	onLoad() {
		const _this = this;
    //初始化插件
    this.mapPlugin = new mapPlugin({
      ak: 'NALBZ-ALBCM-ZFO6I-6L5UY-PDNNQ-RDBVI'
    });
    uni.getLocation({
      type: 'gcj02',
      success: function(res) {
        _this.userLat = res.latitude;
        _this.userLong = res.longitude;
        
        _this.longitude = res.longitude;
        _this.latitude = res.latitude;
      }
    });
	},
	methods: {
		//改变颜色
		changeBg(item) {
			if (item.auditStatus == 'PendingReview' || item.auditStatus == 'Pass') {
				return 'bg-blue text-blue';
			} else if (item.auditStatus == 'UnderReview') {
				return 'bg-success-1 text-primary';
			} else if (item.auditStatus == 'CancelAudit' || item.auditStatus == 'NotPass') {
				return 'bg-error-2 text-error';
			}
		},
		markTap(e) {
			const markerId = e.markerId;
			this.selectedMarker = this.markers.find(marker => marker.id === parseInt(markerId));
			console.log('您点击了标记，详细信息：', this.selectedMarker);
			this.show = true;
      this.$nextTick(() => {
        this.drawRoute(this.selectedMarker.latitude, this.selectedMarker.longitude);
      })
		},
		// 点聚合
		cluster() {
			this._mapContext.initMarkerCluster({
        enableDefaultStyle: false, // 是否使用默认样式
        zoomOnClick: true, // 点击聚合的点，是否改变地图的缩放级别
        gridSize: 40, // 聚合计算时网格的像素大小，默认40
        complete(res) {
          console.log('initMarkerCluster', res);
        }
			});

      this._mapContext.on('markerClusterCreate', res => {
        console.log('markerClusterCreate', res);
        const clusters = res.clusters;
        const markers = clusters.map(cluster => {
          const { center, clusterId, markerIds } = cluster;
          console.log(center, clusterId, markerIds)
          return {
            ...center,
            width: 22,
            height: 30,
            clusterId, // 必须
            iconPath: this.getStaticFilePath('marker.png'),
            callout: {
              content: markerIds.length + '个信息',
              bgColor: '#FFFFFF',
              padding: 6,
              borderRadius: 6,
              textAlign: 'center',
              fontSize: 14,
              color: '#0052d9',
              display: 'ALWAYS',
            }
          };
        });
        this._mapContext.addMarkers({
          markers,
          clear: false,
          complete(res) {
            console.log('clusterCreate addMarkers', res);
          }
        });
			});
			this._mapContext.on('markerClusterClick', res => {
				console.log('markerClusterClick', res);
			});
			this.getProject();
		},

		//我发布的
		getProject() {
			busiInfoMapGetByPage({
				projectName: this.projectName,
				orderBy: this.changeColor ? 1 : 0,
				rootInformationEnum: this.rootInformationEnum == 2 ? '' : this.rootInformationEnum,
				projectStage: this.projectStage == 4 ? '' : this.projectStage,
				size: 9999
			}).then(res => {
				if (res.code == 10000) {
					const data = res.data.data;
					data.forEach((item, index) => {
						this.$set(item, 'id', index);
						this.$set(item, 'latitude', parseFloat(item.latitude));
						this.$set(item, 'longitude', parseFloat(item.longitude));
					});
					this.markers = data;
					// this.latitude = data[0].latitude;
					// this.longitude = data[0].longitude;
					this.addMarkers(data);
				} else {
					this.$u.toast(res.msg);
				}
			});
		},

		//我跟踪的
		busInfoTrackPageFn() {
			busInfoTrackPageList({
				projectName: '',
				orderBy: this.changeColor ? 1 : 0,
				rootInformationEnum: this.rootInformationEnum == 2 ? '' : this.rootInformationEnum,
				projectStage: this.projectStage == 4 ? '' : this.projectStage,
				size: 9999
			}).then(res => {
				if (res.code == 10000) {
					let data = res.data.data;
					data.forEach((item, index) => {
						this.$set(item, 'id', index);
						this.$set(item, 'latitude', parseFloat(item.latitude));
						this.$set(item, 'longitude', parseFloat(item.longitude));
					});
					this.latitude = data[0].latitude;
					this.longitude = data[0].longitude;
					this.markers = data;
					this.addMarkers(data);
				} else {
					this.$u.toast(res.msg);
				}
			});
		},

		//下拉框
		changemyPhaseFn(e) {
			this.tag = e.value;
			if (this.tag == 'iposted') {
				this.getProject();
			} else {
				this.busInfoTrackPageFn();
			}
		},

		searchKeyFn() {
			if (this.tag == 'iposted') {
				this.getProject();
			} else {
				this.busInfoTrackPageFn();
			}
		},

		changeRootInformationEnumFn(e) {
			this.rootInformationEnum = e;
			if (this.tag == 'iposted') {
				this.getProject();
			} else {
				this.busInfoTrackPageFn();
			}
		},
		changeProjectStageFn(e) {
			this.projectStage = e;
			if (this.tag == 'iposted') {
				this.getProject();
			} else {
				this.busInfoTrackPageFn();
			}
		},

		/**
     * @description 添加标记点
     * @param {Object} data
     */
		addMarkers(data) {
			const markers = [];
			data.forEach((p, i) => {
        let contents = [];
        for (let i = 0; i < p.projectName.length; i += 10) {
          contents.push(p.projectName.substr(i, 10));
        }
        markers.push(
          Object.assign({},
            {
              id: p.id,
              iconPath: this.getStaticFilePath('marker.png'),
              width: 18,
              height: 25,
              joinCluster: true, // 指定了该参数才会参与聚合
              callout: {
                content: contents.join('\n'),
                bgColor: '#FFFFFF',
                padding: 6,
                borderRadius: 6,
                textAlign: 'center',
                fontSize: 14,
                color: '#0052d9',
                display: 'ALWAYS',
              }
            },p)
				);
			});
			this._mapContext.addMarkers({
				markers,
				clear: true,
				complete(res) {
					console.log('addMarkers', res);
				}
			});
		},
    /**
     * @description 绘制行车路线
     * @param {Object} lat
     * @param {Object} long
     */
    drawRoute(lat, long) {
      let param = {
        from : {
          latitude: this.userLat,
          longitude: this.userLong
        },
        to: {
          latitude: lat,
          longitude: long
        },
        success: (datas) => {
          const route = datas.result.routes[0];
          var coors = route.polyline, pl = [];
          //坐标解压（返回的点串坐标，通过前向差分进行压缩）
          var kr = 1000000;
          for (var i = 2; i < coors.length; i++) {
            coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
          }
          //将解压后的坐标放入点串数组pl中
          for (var i = 0; i < coors.length; i += 2) {
            pl.push({ latitude: coors[i], longitude: coors[i + 1] })
          }
          this.markerDuration = convertMinutesToHours_minutes(route.duration);
          this.markerDistance = route.distance >= 1000 ? `${(route.distance / 1000).toFixed(1)}公里` : `${route.distance}米`;
          this.polyline = [{
            points: pl,
            color: '#0052d9',
            width: 6,
            borderColor: '#003996',
            borderWidth: 1,
            arrowLine: true,
          }]
          this.$nextTick(() => {
            //调整视野
            this._mapContext.includePoints({
              points: [
                {
                  latitude: this.userLat,
                  longitude: this.userLong
                },{
                  latitude: lat,
                  longitude: long
                },
                ...pl
              ],
              padding: [150, 100, 100, 100]
            })
          })
        }
      }
      this.mapPlugin.execDirection(param);
    },
    
		//项目详情
		projectDetailsFn(item) {
			this.$Router.push({
				path: '/detailPages/pages/projectDetails/index',
				query: {
					busiInfoId: item.busiInfoId
				}
			});
		},
    
    /**
     * @description 唤醒导航
     */
    handleCallNavigator() {
      uni.openLocation({
        latitude: this.selectedMarker.latitude,
        longitude: this.selectedMarker.longitude,
        name: this.selectedMarker.projectAddressName,
      })
    }
	}
};
</script>
<style scoped lang="scss">
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.logo {
	height: 200rpx;
	width: 200rpx;
	margin-top: 200rpx;
	margin-left: auto;
	margin-right: auto;
	margin-bottom: 50rpx;
}

.text-area {
	display: flex;
	justify-content: center;
}

.title {
	font-size: 36rpx;
	color: #8f8f94;
}

.searchBox {
	position: absolute;
	top: 200rpx;
	padding: 0 30rpx;
	width: 680rpx;
	margin: 0 30rpx;
	background-color: #fff;
	// z-index: 10;
	.operateBox {
		width: 320rpx;
	}
}
::v-deep .select-picker {
	width: 200rpx !important;
}

::v-deep .u-content {
	height: 80rpx !important;
}
::v-deep .u-dropdown__content {
	width: 676rpx;
	left: -174rpx;
}
::v-deep .u-dropdown__content__mask {
	background: rgba(0, 0, 0, 0) !important;
}

::v-deep .uicon-search {
	color: #0052d9 !important;
}
::v-deep .u-dropdown__menu__item__text ::after {
	font-family: 'iconfont';
	content: '\eb6d';
	padding-left: 10rpx;
	color: #0052d9;
	font-size: 20rpx;
}
::v-deep .u-dropdown__menu__item__arrow {
	display: none !important;
}

.call-navigator {
  margin-left: 20rpx;
  height: 40rpx;
  padding: 0 20rpx;
  border: 1px solid #0052d9;
  color: #0052d9;
  border-radius: 20rpx;
  display: inline-flex;
  align-items: center;
}
</style>
